import re
from pathlib import Path

from docx.shared import Inches
import csv
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn

def write_csv_to_docx(doc, csv_path):
    # # 创建 Word 文档对象
    # doc = Document()
    # 设置字体为宋体（表格内容）
    def set_cell_font(cell, text, font_size=10.5):
        run = cell.paragraphs[0].add_run(text)
        run.font.name = '宋体'
        run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
        run.font.size = Pt(font_size)
    # 打开 CSV 文件
    with open(csv_path, 'r', encoding='utf-8-sig') as f:
        reader = list(csv.reader(f))
        if not reader:
            print("CSV 文件为空")
            return
        # 创建表格（行数，列数）
        table = doc.add_table(rows=len(reader), cols=len(reader[0]))
        table.style = 'Table Grid'
        # 填充表格内容
        for row_idx, row in enumerate(reader):
            for col_idx, cell_value in enumerate(row):
                cell = table.cell(row_idx, col_idx)
                set_cell_font(cell, cell_value, font_size=10.5)



def markdown_to_docx(md_text, output_path="output.docx"):
    doc = Document()
    # print(md_text)
    lines = md_text.splitlines()

    for line in lines:
        # 插入 PNG 图片
        img_match = re.search(r'!\[.*?\]\(([^)]+\.png)\)', line)
        if img_match:
            img_path = img_match.group(1)
            try:
                doc.add_picture(img_path, width=Inches(5))
            except Exception as e:
                doc.add_paragraph(f"[图片插入失败: {img_path}] 错误: {e}")
            continue

        # 插入 CSV 表格
        csv_match = re.search(r'\[.*?\]\(([^)]+\.csv)\)', line)
        if csv_match:
            csv_path = csv_match.group(1)
            write_csv_to_docx(doc, Path(csv_path))
            continue
        # 其他普通行
        doc.add_paragraph(line)
    doc.save(output_path)

# 示例用法
if __name__ == "__main__":
    with open("D:\\hbyt\\AI智能投标\\markdown_output\\激励及绩效管理_v1.0_2201\\激励及绩效管理_v1.0_2201.md", "r", encoding="utf-8") as f:
        md_content = f.read()
    # con="[点击查看表格内容](D:/hbyt/AI智能投标/markdown_output/media/激励及绩效管理_v1.0_2201/tables/table_0.csv)"
    # raw_str = f'r"{con}"'
    markdown_to_docx(md_content, "结果输出.docx")
